/*
 * Copyright (c) 2018-2022, 四川蜀天梦图数据科技有限公司.
 * All rights reserved.
 */

package link_list

// https://leetcode.cn/problems/rotate-list leetcode-61
func rotateRight(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil || k == 0 {
		return head
	}

	count := k
	var first, second *ListNode
	first = head

	for count > 0 {
		first = first.Next
		count--
		if first == nil {
			break
		}
	}

	if count == 0 && first == nil {
		return head
	}

	if count == 0 {
		second = head
		for ; first != nil && first.Next != nil; first = first.Next {
			second = second.Next
		}

		next := second.Next
		first.Next = head
		second.Next = nil
		return next
	}

	length := k - count
	newK := k % length
	return rotateRight(head, newK)
}
